#!/usr/bin/ruby
#-*- coding: UTF-8 -*-
require 'xcodeproj'
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8

tempPath = "#{File.dirname(__FILE__)}/forAddSdkCertificate.plist"
project_path = ARGV[0]
provision_path = ARGV[1]
provision_type = ARGV[2]

platform_project = Xcodeproj::Project.open(project_path)
platform_target = platform_project.targets[0]
puts "temp path #{tempPath}"
system("security cms -D -i #{provision_path} > #{tempPath}")
file_content_hash = Xcodeproj::Plist.read_from_path(tempPath)
system("rm -rf #{tempPath}")

team_identifier = file_content_hash['TeamIdentifier'].first
team_name = file_content_hash["TeamName"]

code_sign_identify = "iPhone #{provision_type}: #{team_name} (#{team_identifier})"

if provision_type == "Developer"
	tempPath = "#{File.dirname(__FILE__)}/ForAddSDKTemp.text"
    puts "temp path #{tempPath}"
	system("security find-identity -v -p codesigning > #{tempPath}")
	temp_file = File.new(tempPath, "r+")
	if temp_file
		contents = temp_file.read()
		pre_str = "iPhone Developer: #{team_name} "
		code_sign_identify = contents[/#{pre_str}\(\w*\)/]
		if code_sign_identify.empty?
			puts "please install dev P12"
		end
		system("rm -rf #{tempPath}")
	else
		puts "get Developer P12 message error"
	end
end

code_sign_identify_sdk = code_sign_identify
provisioning_profile = file_content_hash["UUID"]

puts "start to config"
platform_target.build_configurations.each do |build_config|
#	puts config.name
#	puts config.build_settings
# if config.name == 'Debug'
	config_hash = build_config.build_settings
	config_hash.each do |key, value|
		#print key, " is ", value, "\n"
		if key == "CODE_SIGN_IDENTITY"
			config_hash["CODE_SIGN_IDENTITY"] = code_sign_identify
		end
		if key == "CODE_SIGN_IDENTITY[sdk=iphoneos*]"
			config_hash["CODE_SIGN_IDENTITY[sdk=iphoneos*]"] = code_sign_identify_sdk
		end
		if key == "PROVISIONING_PROFILE"
			config_hash["PROVISIONING_PROFILE"] = provisioning_profile
		end
	end
# end
end
puts "end config"
puts "\n"
puts "save modify"
platform_project.save
